/**
* Tcp 
* 针对底层的tcp包的封包解包获取头信息
*/
class TcpPk{

   // 处理粘包问题,并且返回订阅者整包。
   get(sk, sockets, cb = () => {}){
       const P = 4;
      // console.log(sk, sockets, cb);
      sk.on('data', (data) => {
          // 获取剩余的字节
          const surplus = sockets.get(sk);
          let mgData = null;
          if(surplus){
              mgData = Buffer.concat([surplus, data], surplus.length + data.length);
              data = mgData;
          }

          while(true){
          let p = P;
          const readSize = this.read_pk_head(data);
          // 看看能否读取一个整包
          let rdbody = this.read_pk_body(readSize, data, p);
          if(rdbody){
              cb(rdbody);
              // data 设置偏移量
              p += readSize;
              // data后移动
              const m = Buffer.allocUnsafe(data.length - p);
              data.copy(m, 0, p, data.length);
              data = m;  
          }else{
              // 存取残余包
              const emem = data.length - p > 0 ?  p : (p > P ? -1 : 0);
              if(emem > -1){
                  const sbuf = Buffer.allocUnsafe(data.length - emem);
                  data.copy(sbuf, 0, emem, data.length);
                  sockets.set(sk, sbuf);          
              }
              break;
          }
       }
      })

   }

   // 封包
   encodeMsg(str = ""){
       const head = Buffer.allocUnsafe(4);
       const body = Buffer(str);
       head.writeInt32LE(str.length);

       return Buffer.concat([head, body], head.length + body.length);
   }


  // 读取包头
  read_pk_head(data){
    let rt = '';

    try{
        rt = data.readInt32LE(0)
    }catch(e){

    }
    return rt;     
  }
  // 读取包的内容如果不足整包大小返回0
  read_pk_body(readSize = 0, data, p){
      let rt = 0;
      if(readSize && data && data.length - p - readSize >= 0){
        // 创建拷贝缓冲区
        const cpBuf = Buffer.allocUnsafe(readSize);
        // console.log(data, p, p+readSize);
        // 拷贝
        data.copy(cpBuf, 0, p, p+readSize);
        rt = cpBuf;
      }

      return rt;
  }

}
module.exports = TcpPk;
